const express = require('express');
const http = require('http');
const https = require('https');
const httpProxy = require('http-proxy');

// 创建 Express 应用
const app = express();

// 设置静态文件目录，例如 'public' 文件夹
app.use(express.static('h5'));

// 创建HTTP代理服务器
const proxy = httpProxy.createProxyServer({
  secure: false,
  agent: new https.Agent({
    checkServerIdentity: () => undefined
  }),
  changeOrigin: true,
  xfwd: true,
  error: (err, req, res) => {
    console.error('代理服务器错误:', err);
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('An error occurred during the proxy');
  }
});

proxy.on('proxyRes', (proxyRes, req, res) => {
  proxyRes.headers['Access-Control-Allow-Origin'] = '*';
  proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
  proxyRes.headers['Access-Control-Allow-Headers'] = 'Content-Type, application/x-www-form-urlencoded';
});

// 创建HTTP服务器，并使用 Express 应用
const server = http.createServer((req, res) => {
  // 代理请求
  proxy.web(req, res, {
    target: 'https://cartier-invite-prod.skyelook.com' // 目标HTTPS服务器地址
  });
});

// 监听端口
server.listen(3000, () => {
  console.log('HTTP Proxy Server running on port 3000');
});